package com.feel.mall.orderservice.service;

import cn.hutool.core.util.IdUtil;
import com.feel.mall.common.bean.*;
import com.feel.mall.common.exception.FeelException;
import com.feel.mall.common.service.AddrService;
import com.feel.mall.common.service.GoodsService;
import com.feel.mall.common.service.OrderService;
import com.feel.mall.common.service.UserService;
import com.feel.mall.orderservice.mapper.CartMapper;
import com.feel.mall.orderservice.mapper.OrderDetailMapper;
import com.feel.mall.orderservice.mapper.OrderMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Author: 刘永钦
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartMapper cartMapper;

    @DubboReference
    private AddrService addrService;
    @DubboReference
    private GoodsService goodsService;
    @DubboReference
    private UserService userService;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void addInfo(OrderVO orderVO) throws FeelException {
        // 创建订单对象
        Order order = new Order();
        // 生成订单id
        String idStr = IdUtil.getSnowflakeNextIdStr();
        // 设置订单id
        order.setId(idStr);
        orderVO.setOrderId(idStr);

        // 获取地址信息
        Addr addr = addrService.getById(orderVO.getAddrId(), orderVO.getUserId());
        // 设置地址详情
        order.setAddrDetail(
                addr.getProvince() + " " + addr.getCity() + " "
                        + addr.getDistrict() + " " + addr.getAddress() + " "
                        + addr.getContact() + " " + addr.getPhone()
        );
        // 设置
        order.setProvince(addr.getProvince());
        order.setUserId(orderVO.getUserId());
        order.setPayType(0);
        order.setAddrId(orderVO.getAddrId());
        order.setStatus(0);

        // 生成订单
        orderMapper.addInfo(order);

        // 生成详情
        for (Integer cartId : orderVO.getCartId()) {
            Cart cart = cartMapper.getById(cartId);
            if (cart == null) {
                throw new FeelException("错误---购物车不存在");
            }
            if (!cart.getUserId().equals(orderVO.getUserId())) {
                throw new FeelException("权限错误");
            }
            // 获取商品信息
            Goods goods = goodsService.selectById(cart.getGoodsId());
            if (goods == null) {
                throw new FeelException("商品不存在，无法生成订单");
            }
            if (goods.getStatus().equals(0)) {
                throw new FeelException("商品下降，无法生成订单");
            }
            if (goods.getCount() < cart.getCount()) {
                throw new FeelException("商品库存不足，无法购买");
            }
            // 商品减去库存
            goods.setCount(goods.getCount() - cart.getCount());
            // 更新商品信息
            goodsService.update(goods);
            // 生成商品详情
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCount(cart.getCount());
            orderDetail.setGoodsId(goods.getId());
            orderDetail.setPrice(goods.getPrice());
            orderDetail.setOrderId(idStr);

            orderDetailMapper.insert(orderDetail);
            // 删除购买商品对应的购物车信息
            cartMapper.delInfo(cart.getId());
        }

    }

    @Override
    public Object selectAll(Order condition, Integer pageNum, Integer pageSize) {

        if (pageNum == null) {
            List<Order> list = orderMapper.selectByCondition(condition);
            list.stream()
                    .forEach(item -> {
                        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(item.getId());
                        item.setOrderDetails(detailList);
                        // 返回数据集需要映射处理
                        detailList.forEach(detail -> {
                            detail.setGoods(goodsService.selectById(detail.getGoodsId()));
                        });
                        item.setUser(userService.selectById(item.getUserId()));
                    });
            return list;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Order> list = orderMapper.selectByCondition(condition);
        list.stream()
                .forEach(item -> {
                    List<OrderDetail> detailList = orderDetailMapper.getByOrderId(item.getId());
                    item.setOrderDetails(detailList);
                });
        PageInfo<Order> pageInfo = new PageInfo<>(list);

        // 返回数据集需要映射处理
        pageInfo.getList()
                .forEach(item -> {
                    List<OrderDetail> detailList = orderDetailMapper.getByOrderId(item.getId());
                    item.setOrderDetails(detailList);
                    // 返回数据集需要映射处理
                    detailList.forEach(detail -> {
                        detail.setGoods(goodsService.selectById(detail.getGoodsId()));
                    });
                    item.setUser(userService.selectById(item.getUserId()));
                });
        return pageInfo;
    }

    @Override
    public Order selectById(String id) throws FeelException {
        // 对用户做映射
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new FeelException("订单不存在，请重试");
        }
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        detailList.forEach(detail -> {
            detail.setGoods(goodsService.selectById(detail.getGoodsId()));
        });
        order.setOrderDetails(detailList);
        User user = userService.selectById(order.getUserId());
        order.setUser(user);
        return order;
    }

    @Override
    public void sendGoods(Order order) throws FeelException {
        //     检查订单是否支付
        Order localorder = this.selectById(order.getId());
        if (!localorder.getStatus().equals(1) && localorder.getStatus().equals(0)) {
            throw new FeelException("订单未支付，请在支付后发货");
        }
        if (localorder.getStatus() > 1) {
            throw new FeelException("商品已经发货");
        }
        //     生成订单编号
        String id = IdUtil.getSnowflakeNextIdStr();
        order.setExpress(id);
        order.setStatus(2);

        orderMapper.updateInfo(order);
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public Boolean pay(String orderId, String payPassword, Integer userId) throws FeelException {
        // 查询订单
        Order order = selectById(orderId);
        // 判断订单是否存在
        if (order == null) {
            throw new FeelException("订单不存在");
        }
        // 是否是用户订单
        if (!order.getUserId().equals(userId)) {
            throw new FeelException("订单权限错误，订单不属于用户");
        }
        // 订单状态
        if (!order.getStatus().equals(0)) {
            throw new FeelException("订单状态错误");
        }

        // 设置订单状态
        order.setStatus(1);
        order.setPayType(0);


        // 查询用户
        User user = userService.selectById(userId);
        // 判断密码
        if (user.getPayPassword() == null) {
            throw new FeelException("支付密码为空，请设置后再下单");
        }
        //  调用服务判断密码是否正确
        if (!userService.verifyPayPassword(payPassword, userId)) {
            throw new FeelException("密码错误请重试");
        }
        // 计算订单金额
        BigDecimal sum = new BigDecimal("0");
        for (OrderDetail orderDetail : order.getOrderDetails()) {
            BigDecimal count = new BigDecimal(orderDetail.getCount());
            BigDecimal price = orderDetail.getPrice();
            sum = sum.add(price.multiply(count));
        }

        if (user.getMoney().compareTo(sum) < 0) {
            throw new FeelException("余额不足，无法支付");
        }

        //  扣钱
        User localUser = new User();
        localUser.setId(userId);
        localUser.setMoney(user.getMoney().subtract(sum));
        // 更新用户信息
        userService.updateInfo(localUser);
        // 更新订单
        orderMapper.updateInfo(order);
        return true;
    }

    /**
     *
     * @return { name: '北京', value: 500 }
     */
    @Override
    public List<Map<String, Integer>> getInfoForEcharts() {
        List<Map<String, Integer>> info = orderMapper.getInfoForEcharts();
        return info;
    }

    @Override
    public Boolean updateInfo(Order order, Integer userId) throws FeelException {
        // 查询订单信息
        Order localOrder = this.selectById(order.getId());
        if (localOrder == null) {
            throw new FeelException("订单不存在");
        }
        if (userId != null) {
            User user = userService.selectById(userId);
            if (user == null) {
                throw new FeelException("用户不存在");
            }
            if (!localOrder.getUserId().equals(userId)) {
                throw new FeelException("权限错误");
            }
        }

        if (order.getStatus() != null && order.getStatus() > 2) {
            if (localOrder.getStatus() < 2) {
                throw new FeelException("错误，请检查订单后重试");
            }
            if (order.getStatus() > 3) {
                // todo 提交反馈申请
            }
        }
        // 执行更新操作
        orderMapper.updateInfo(order);
        return true;
    }
}
